const apiUrl = "http://matrixai-faucet.contractlab.net:9708/transfer";
let timeout,
  isLoading = false;
$(function () {
  $(".el-button-primary").click(submit);
  document.onkeydown = function (event) {
    e = event ? event : window.event ? window.event : null;
    if (e.keyCode == 13) {
      submit();
    }
  };
  function submit() {
    let addr = $(".input-addr").val();
    if (!addr) {
      return msg("error", "please input your address.", 2);
    }
    if (addr.length < 32) {
      return msg("error", "please input right address.", 2);
    }
    if (isLoading) {
      return msg("error", "please waiting.", 2);
    }
    // ajax('https://example-datastore.cess.cloud/store/faucet/publickey',{addr:addr},function(json){
    // json=JSON.parse(json);
    ajax(apiUrl, JSON.stringify({ Address: addr }), (t) => {
      if (t.Status && t.Status == "Success") {
        if (t.Result.AsInBlock) {
          msg("ok", "Submitted successfully!");
        } else {
          msg("error", "Only submitted once in 24 hours.", 6);
        }
      } else {
        msg("error", t.Result.Err);
      }
    });
    // let publickeyUrl = "/api/polkadot/to-publickey";
    // ajax(publickeyUrl, { addr: addr }, function (json) {
    //   if (json.msg != "ok") {
    //     return msg("error", json.msg, 6);
    //   }
    //   addr = json.data;
    //   ajax(apiUrl, JSON.stringify({ Address: addr }), (t) => {
    //     if (t.Status && t.Status == "Success") {
    //       if (t.Result.AsInBlock) {
    //         msg("ok", "Submitted successfully!");
    //       } else {
    //         msg("error", "Only submitted once in 24 hours.", 6);
    //       }
    //     } else {
    //       msg("error", t.Result.Err);
    //     }
    //   });
    // });
  }
  function ajax(url, params, cb) {
    loading(true);
    $.ajax({
      type: "POST",
      url: url,
      data: params,
      success: function (json) {
        cb(json);
      },
      error: function (e) {
        let json = JSON.parse(e.response);
        console.log(e);
        msg("error", json.Result.Err, 10);
      },
      complete: function () {
        loading(false);
      },
    });
  }
  function msg(type, txt, autoCloseSec) {
    clearTimeout(timeout);
    if (!txt) {
      return $(".tips").slideUp("slow");
    }
    $(".tips")
      .slideDown("slow")
      .html('<div class="tips-' + type + '">' + txt + "</div>");
    if (autoCloseSec) {
      timeout = setTimeout(msg, autoCloseSec * 1000);
    }
  }
  function loading(isShow) {
    isLoading = isShow;
    if (isShow) {
      msg("loading", "loading");
      $(".el-button-primary").hide();
      $(".el-button-disabled").show();
    } else {
      $(".el-button-primary").show();
      $(".el-button-disabled").hide();
    }
  }
});
